using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using CaipuGuanliXitong.Models;
using System.Text.Json;
using System.Linq;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System;

namespace CaipuGuanliXitong.Controllers;

public class WeeklyMenuController : Controller
{
    private readonly CookBookDbContext _context;

    public WeeklyMenuController(CookBookDbContext context)
    {
        _context = context;
    }

    // GET: WeeklyMenu
    public IActionResult Index(DateTime? startDate)
    {
        // 如果没有指定开始日期，则使用本周一
        if (!startDate.HasValue)
        {
            startDate = DateTime.Now.Date;
            while (startDate.Value.DayOfWeek != DayOfWeek.Monday)
            {
                startDate = startDate.Value.AddDays(-1);
            }
        }
        
        // 查询一周的菜单
        var weeklyMenus = _context.WeeklyMenus.GetList(x => x.WeekStartDate == startDate);
        
        // 获取所有菜谱用于下拉框
        ViewBag.CookBooks = _context.CookBooks.GetList();
        ViewBag.StartDate = startDate.Value;
        
        return View(weeklyMenus);
    }

    // GET: WeeklyMenu/ExportToExcel
    public IActionResult ExportToExcel(DateTime? startDate)
    {
        // 如果没有指定开始日期，则使用本周一
        if (!startDate.HasValue)
        {
            startDate = DateTime.Now.Date;
            while (startDate.Value.DayOfWeek != DayOfWeek.Monday)
            {
                startDate = startDate.Value.AddDays(-1);
            }
        }
        
        // 查询一周的菜单
        var weeklyMenus = _context.WeeklyMenus.GetList(x => x.WeekStartDate == startDate);
        
        // 构建CSV内容
        var csv = new StringBuilder();
        
        // 添加标题行
        csv.AppendLine("星期,早餐(男),早餐(女),午餐(男),午餐(女),晚餐(男),晚餐(女)");
        
        // 定义星期和餐次
        string[] weekdays = { "周一", "周二", "周三", "周四", "周五", "周六", "周日" };
        int[] dayNumbers = { 1, 2, 3, 4, 5, 6, 7 };
        int[] mealNumbers = { 1, 2, 3 }; // 1=早餐, 2=午餐, 3=晚餐
        int[] genders = { 1, 2 }; // 1=男, 2=女
        
        // 添加数据行
        for (int i = 0; i < weekdays.Length; i++)
        {
            var row = new List<string> { weekdays[i] };
            
            // 每餐两种性别
            for (int j = 0; j < mealNumbers.Length; j++)
            {
                for (int k = 0; k < genders.Length; k++)
                {
                    var menu = weeklyMenus.FirstOrDefault(m => 
                        m.DayOfWeek == dayNumbers[i] && 
                        m.MealType == mealNumbers[j] && 
                        m.Gender == genders[k]);
                    
                    if (menu != null)
                    {
                        if (!string.IsNullOrEmpty(menu.CookBookNames))
                        {
                            // 多个菜谱名称
                            row.Add(menu.CookBookNames.Replace(",", "、"));
                        }
                        else if (!string.IsNullOrEmpty(menu.CookBookName))
                        {
                            // 单个菜谱名称
                            row.Add(menu.CookBookName);
                        }
                        else
                        {
                            row.Add("");
                        }
                    }
                    else
                    {
                        row.Add("");
                    }
                }
            }
            
            csv.AppendLine(string.Join(",", row.Select(field => $"\"{field}\"")));
        }
        
        // 将CSV内容转换为字节
        var bytes = Encoding.UTF8.GetBytes(csv.ToString());
        
        // 返回CSV文件
        var fileName = $"每周菜谱_{startDate.Value:yyyyMMdd}.csv";
        return File(bytes, "text/csv", fileName);
    }

    // GET: WeeklyMenu/Details/5
    public IActionResult Details(DateTime startDate)
    {
        // 确保startDate是周一
        while (startDate.DayOfWeek != DayOfWeek.Monday)
        {
            startDate = startDate.AddDays(-1);
        }
        
        // 获取一周的菜单数据
        var weeklyMenus = _context.WeeklyMenus.GetList(x => x.WeekStartDate == startDate);
        
        if (weeklyMenus.Count == 0)
        {
            // 如果没有数据，返回空列表
            ViewBag.StartDate = startDate;
            return View(new List<WeeklyMenu>());
        }
        
        ViewBag.StartDate = startDate;
        
        return View(weeklyMenus);
    }

    // GET: WeeklyMenu/Edit/5
    public IActionResult Edit(DateTime startDate)
    {
        // 确保startDate是周一
        while (startDate.DayOfWeek != DayOfWeek.Monday)
        {
            startDate = startDate.AddDays(-1);
        }
        
        // 获取一周的菜单数据，如果没有则创建
        var weeklyMenus = _context.WeeklyMenus.GetList(x => x.WeekStartDate == startDate);
        
        if (weeklyMenus.Count == 0)
        {
            // 初始化一周的菜单数据 (每天每餐每性别)
            for (int day = 1; day <= 7; day++)
            {
                for (int meal = 1; meal <= 3; meal++)
                {
                    for (int gender = 1; gender <= 2; gender++)
                    {
                        var menu = new WeeklyMenu
                        {
                            WeekStartDate = startDate,
                            DayOfWeek = day,
                            MealType = meal,
                            Gender = gender,
                            CookBookId = null,
                            CookBookName = null,
                            CookBookIds = null,
                            CookBookNames = null,
                            CreatedTime = DateTime.Now,
                            UpdatedTime = DateTime.Now
                        };
                        _context.WeeklyMenus.Insert(menu);
                    }
                }
            }
            weeklyMenus = _context.WeeklyMenus.GetList(x => x.WeekStartDate == startDate);
        }
        
        ViewBag.CookBooks = _context.CookBooks.GetList();
        ViewBag.StartDate = startDate;
        
        return View(weeklyMenus);
    }

    // POST: WeeklyMenu/Edit
    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult Edit(DateTime startDate, string menuDataJson)
    {
        // 确保startDate是周一
        while (startDate.DayOfWeek != DayOfWeek.Monday)
        {
            startDate = startDate.AddDays(-1);
        }
        
        // 解析JSON数据
        var menuData = JsonSerializer.Deserialize<Dictionary<string, int[]>>(menuDataJson) ?? new Dictionary<string, int[]>();
        
        foreach (var item in menuData)
        {
            // 解析键名，格式为 "Day{day}_Meal{meal}_Gender{gender}"
            var parts = item.Key.Split('_');
            if (parts.Length == 3)
            {
                var dayPart = parts[0].Replace("Day", "");
                var mealPart = parts[1].Replace("Meal", "");
                var genderPart = parts[2].Replace("Gender", "");
                
                if (int.TryParse(dayPart, out int dayOfWeek) && 
                    int.TryParse(mealPart, out int mealType) && 
                    int.TryParse(genderPart, out int gender))
                {
                    var menu = _context.WeeklyMenus.GetSingle(x => 
                        x.WeekStartDate == startDate && 
                        x.DayOfWeek == dayOfWeek && 
                        x.MealType == mealType && 
                        x.Gender == gender);
                    
                    if (menu != null)
                    {
                        // 处理多个菜谱ID
                        var cookBookIds = item.Value;
                        if (cookBookIds != null && cookBookIds.Length > 0)
                        {
                            // 获取菜谱名称
                            var cookBookNames = new List<string>();
                            var validCookBookIds = new List<int>(); // 只保留有效ID
                            foreach (var id in cookBookIds)
                            {
                                var cookBook = _context.CookBooks.GetSingle(x => x.Id == id);
                                if (cookBook != null)
                                {
                                    cookBookNames.Add(cookBook.Name);
                                    validCookBookIds.Add(id); // 只添加有效的ID
                                }
                            }
                            
                            // 只有当有有效菜谱时才更新字段
                            if (validCookBookIds.Count > 0)
                            {
                                menu.CookBookIds = string.Join(",", validCookBookIds);
                                menu.CookBookNames = string.Join(",", cookBookNames);
                                
                                // 保持原有的单个菜谱字段以保证向后兼容
                                menu.CookBookId = validCookBookIds[0];
                                menu.CookBookName = cookBookNames.FirstOrDefault();
                            }
                            else
                            {
                                // 如果没有有效菜谱，清空所有字段
                                menu.CookBookIds = null;
                                menu.CookBookNames = null;
                                menu.CookBookId = null;
                                menu.CookBookName = null;
                            }
                        }
                        else
                        {
                            menu.CookBookIds = null;
                            menu.CookBookNames = null;
                            menu.CookBookId = null;
                            menu.CookBookName = null;
                        }
                        
                        menu.UpdatedTime = DateTime.Now;
                        _context.WeeklyMenus.Update(menu);
                    }
                }
            }
        }
        
        return RedirectToAction(nameof(Index), new { startDate = startDate });
    }
    
    // GET: WeeklyMenu/Delete/5
    public IActionResult Delete(DateTime startDate)
    {
        // 确保startDate是周一
        while (startDate.DayOfWeek != DayOfWeek.Monday)
        {
            startDate = startDate.AddDays(-1);
        }
        
        // 获取一周的菜单数据
        var weeklyMenus = _context.WeeklyMenus.GetList(x => x.WeekStartDate == startDate);
        
        ViewBag.StartDate = startDate;
        
        return View(weeklyMenus);
    }

    // POST: WeeklyMenu/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public IActionResult DeleteConfirmed(DateTime startDate)
    {
        // 软删除指定周的所有菜单数据
        var weeklyMenus = _context.WeeklyMenus.AsQueryable().Where(x => x.WeekStartDate == startDate).ToList();
        foreach (var menu in weeklyMenus)
        {
            menu.IsDeleted = true;
            menu.UpdatedTime = DateTime.Now;
        }
        _context.WeeklyMenus.UpdateRange(weeklyMenus);
        
        return RedirectToAction(nameof(Index), new { startDate = startDate });
    }
}